//
//  PostDetailsViewController.swift
//  ZCF
//
//  Created by 赵世杰 on 16/4/21.
//  Copyright © 2016年 zhaoshijie. All rights reserved.
//

import UIKit

class PostDetailsViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource{
    
    /// 数据
    
    // 请求的参数id
    var messagedId:String!
    // 网络请求的数据存储对象
    var communityDetails_model:CommunityDetails_PostDetails!
    // 当前请求页
    var pageNumber:Int!
    // 一共的页数
    var totalPage:Int!
    // 存储评论视图的数字
    var communitArray:Array<AnyObject>!
    
    

    
    /// 视图
    
    //  头视图
    var headerView:PostDetailsHeaderView!
    
    @IBOutlet var overallTableView: UITableView!
    @IBOutlet var textField: UITextField!
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.setTabBarHidden()
        self.navigationController?.navigationBar.isHidden = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.setTabBarNoHidden()
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化数据
        self._initDataList()
        
        // 创建视图
        self._initViews()
        
        // 网络请求数据
        self._requestDataList()
    }
    
    //MARK: - 初始化数据
    func _initDataList()
    {
        self.pageNumber = 1
        self.communitArray = Array<AnyObject>()
        self.totalPage = 2
    }
    
    //MARK: - 创建视图
    func _initViews()
    {
        
        // 设置自适应
        self.overallTableView.delegate = self
        self.overallTableView.dataSource = self
        // 注册单元格
        self.overallTableView .register(UINib(nibName: "PostDetailsCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        // 添加底部的视图
    }
    
    
    // 需要刷新的方法
    func requestSuccessNext()
    {
        self.headerView = Bundle.main.loadNibNamed("PostDetailsHeaderView", owner: nil, options: nil)?.last as! PostDetailsHeaderView
        self.headerView.height = self.computerHeaderHeight()
        self.headerView.postDetails_model = self.communityDetails_model
        self.overallTableView.tableHeaderView = self.headerView
        self.overallTableView.tableHeaderView?.height = self.computerHeaderHeight()
        self.overallTableView.rowHeight = UITableViewAutomaticDimension
        self.overallTableView.estimatedRowHeight = 100
        self.overallTableView.addHeader(withTarget: self, action: #selector(PostDetailsViewController.refreshHeaderAction))
        self.overallTableView.addFooter(withTarget: self, action: #selector(PostDetailsViewController.refreshFooterAction))
        
        self.overallTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: KScreenWidth, width: 1, height: 0))
        
    }

    //MARK: - 请求数据
    func _requestDataList()
    {
        // 请求头部视图的数据
        self.requestHeader()
        // 请求评论内容的数据
        self.requestCommentContent(PullState.dropDown)
    }
    
    // 请求头部视图的数据
    func requestHeader()
    {
        let urlString = HttpUrl + "/bbs/get"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let paramDic:[String:String] = ["id":self.messagedId]
//        print(self.messagedId)
        let request = HTTPRequest()
        let cbindicatorView = CBIndicatorView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        self.view.addSubview(cbindicatorView)
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters: paramDic, resultBlock: { (result) -> Void in
            //            print("请求成功")
//            print(result)
            cbindicatorView.removeFromSuperview()
            let data:[String:AnyObject] = result["data"] as! Dictionary
            self.communityDetails_model = CommunityDetails_PostDetails(contentDic:data)
            // 刷新
            self.requestSuccessNext()
            self.overallTableView .reloadData()
            }) { () -> Void in
                print("请求失败")
                cbindicatorView.removeFromSuperview()
        }
        
    }
    
    // 请求评论内容的数据
    func requestCommentContent(_ state:PullState)
    {
        let urlString = HttpUrl + "/bbs/reply/page/get"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let paramDic:[String:String] = ["bbsThreadId":self.messagedId ,"page":String(self.pageNumber)]
        let request = HTTPRequest()
//        print(self.pageNumber)
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters: paramDic, resultBlock: { (result) -> Void in
//            print(result)
            let data:[String:AnyObject] = result["data"] as! Dictionary
            self.totalPage = Int(data["totalPage"] as! NSNumber)
            let list:Array<AnyObject> = data["list"] as! Array
            for dic:AnyObject in list
            {
                let commentModel_community = CommentModel_community(contentDic:dic as! [AnyHashable: Any])
                self.communitArray.append(commentModel_community!)
            }
            self.pageNumber = self.pageNumber + 1
            // 关闭刷新
            self.removeRefresh()
            self.overallTableView.reloadData()
            
            }) { () -> Void in
                print("请求失败")
                
        }
    }
    
    
    //MARK: - 上拉加载下拉刷新
    func refreshHeaderAction()
    {
        self.communitArray.removeAll()
        self.pageNumber = 1
        self.requestCommentContent(PullState.dropDown)
    }
    
    func refreshFooterAction()
    {
        if self.pageNumber < self.totalPage
        {
            self.requestCommentContent(PullState.pullOn)
        }
        else
        {
            let prompt = SJPromptView()
            prompt.textString = "已经是最后一页了"
            prompt.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight - 100, width: KScreenWidth-200, height: 30), withTime: 1)
            self.overallTableView.footerEndRefreshing()
        }
        
    }
    
    
    //MARK: - 响应方法
    @IBAction func commentPublishAction(_ sender: AnyObject) {
    
        
    }
    
    
    //MARK: - 移除刷新视图
    func removeRefresh()
    {
        if self.overallTableView.isHeaderRefreshing
        {
            self.overallTableView.headerEndRefreshing()
        }
        if self.overallTableView.isFooterRefreshing
        {
            self.overallTableView.footerEndRefreshing()
        }
    }
    
    //MARK: - tableView的代理和数据源方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.communitArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PostDetailsCell
        
        cell.selectionStyle = .none
        cell.commentModel_community = self.communitArray[(indexPath as NSIndexPath).row] as! CommentModel_community
        cell.setNeedsLayout()
        return cell
    }
    

//    // 计算头视图的高度
    func computerHeaderHeight() -> CGFloat
    {
        var imageHeight:CGFloat = 10 + 50
        if (!self.communityDetails_model.title.isEmpty)
        {
            imageHeight = imageHeight + 10 + self.textLabelheight(self.communityDetails_model.title, size: 17)
        }
        else
        {
            imageHeight = imageHeight + 10
        }
        if (!self.communityDetails_model.content.isEmpty)
        {
            imageHeight = imageHeight + 1 + self.textLabelheight(self.communityDetails_model.content, size: 17)
        }
        else
        {
            imageHeight = imageHeight + 1
        }
        
        if (!self.communityDetails_model.imageList.isEmpty)
        {
            if self.communityDetails_model.imageList.count <= 3
            {
                imageHeight = imageHeight + 2 + (KScreenWidth - 30)/3.0
            }
            else if self.communityDetails_model.imageList.count <= 6
            {
                imageHeight = imageHeight + 2 + (KScreenWidth - 30)/3.0*2 + 5
            }
            else
            {
                imageHeight = imageHeight + 2 + (KScreenWidth - 30)/3.0*3 + 10
            }

        }
        imageHeight = imageHeight + 20 + 30 + 34
        return imageHeight
    }
    
    //MARK: - 计算文本的高度
    func textLabelheight(_ textString:String , size:CGFloat) -> CGFloat
    {
        let attributus = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: size)]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let text:NSString = NSString(cString: textString.cString(using: String.Encoding.utf8)!, encoding: String.Encoding.utf8.rawValue)!
        let rect = text.boundingRect(with: CGSize(width: KScreenWidth-20, height: CGFloat.greatestFiniteMagnitude), options: option, attributes: attributus, context: nil)
        return rect.height
    }

    

}
